<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {
	function User() {
		parent::__construct();
		$this->load->model('user_model');
	}

	public function index() {
		$this->load->view('login');
	}

	public function login() {
		$user_name = $this->input->post('user_name');
		$password  = $this->input->post('password');
		$users     = $this->user_model->get_by_name($user_name);
		if(empty($users)) {
			echo "<script>alert('this user not exits');window.history.go(-1);</script>";
			
		} elseif (!empty($users) && $users['password'] == md5($password)) {
			$this->session->set_userdata('user_id',$users['user_id']);
			$this->session->set_userdata('user_name',$users['user_name']);
			$this->session->set_userdata('role_id',$users['role_id']);
			$this->session->set_userdata('logged_in',TRUE);
			redirect('/report');
		} else {
			echo "<script>alert('Wrong password!');window.history.go(-1);</script>";
		}

	}

	public function logout() {
		$this->session->unset_userdata('user_id');
        $this->session->unset_userdata('user_name');
        $this->session->unset_userdata('role_id');
    	$this->session->set_userdata('logged_in',FALSE);
    	redirect('/user');
	}

	public function add() {
		$user_name = $this->input->post('user_name');
		$password  = $this->input->post('password');
		$role_id   = $this->input->post('role_id');
		$users     = $this->user_model->get_by_name($user_name);
		if (!empty($users)) {
			echo "<script>alert('user have existed');window.history.go(-1);</script>";
		} else {
			$this->user_model->add($user_name, md5($password), $role_id);
			redirect('/user/user_edit');
		}
	}

	public function delete() {
		$user_id = $this->input->get('user_id');
		$user_ids = $this->user_model->get_by_id($user_id);
	    if (!empty($user_ids)) {
	    	$this->user_model->delete($user_id);
	    } else {
	    	echo "<script>alert('Not existed');window.history.go(-1);</script>";
	    }
	    redirect("/user/user_edit");
	}

	public function update() {
		$user_id   = $this->input->post('user_id');
		$user_name = $this->input->post('user_name');
		$password  = $this->input->post('password');
		$role_id   = $this->input->post('role_id'); 
		$this->user_model->update($user_id, $user_name, md5($password), $role_id);
		redirect("/user/user_edit");
	}

	public function user_edit() {
		$users = $this->user_model->get_user_list();
		foreach ($users as $row) {
			$user_id   = $row['user_id'];
			$user_name = $row['user_name'];
			$password  = md5($row['password']);
			$role_id   = $row['role_id'];
			$user_info['users'][] = array(
				'user_id'   => $user_id,
				'user_name' => $user_name,
				'password'  => $password,
				'role_id'	=> $role_id
			);
		}
		$user_infos = $user_info['users'];
		$this->load->view('user',  array('user_infos' => $user_infos));
	}

}

